import React from 'react';
import { ColumnProps } from 'antd/lib/table';
import { Input, InputNumber, Select, Button } from 'antd';
import _ from 'lodash';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import md5 from 'blueimp-md5';
import {
  checkShowOpt,
  getStyle,
  StateType,
  toMerchantStatus,
  toPaymentType,
  toRepairStatus,
  toUserType,
  urlEncode,
} from '../utils';
import { toTime, currency, getElliStyleElement } from '@/utils/tools';
import { LOGS_STATUS, RECHARGE_TRANSFER_TYPE_NAMES, REMARK_STATUS } from '../data';
import styles from './style.less';
import { getLogin } from '@/utils/auth';
import { checkPermission } from '@/utils/resolvePermission';
// insert into gl_system_menu values(50010200, '补单',
// 'new-finance-report-abnormal-export', '', '', 1, 0, 500402, 'admin', now());

const { Option } = Select;

interface SignParamsType {
  device_id?: string;
  os_type?: number;
  timestamp?: number;
  version?: string;
  token?: string | undefined;
  uid?: string | undefined;
  sign?: string;
}

export function toRechargeType(val: number): string {
  const obj = _.find(RECHARGE_TRANSFER_TYPE_NAMES, item => item.value === val);
  return obj ? obj.title : '';
}

export function addSign(): object {
  const timestamp = Date.parse(new Date().toString());
  const signParams: SignParamsType = {};
  const { token, uid } = getLogin();
  signParams.device_id = '1.0';
  signParams.os_type = 0;
  signParams.timestamp = timestamp;
  signParams.version = '1.0';
  const urlStr = urlEncode(signParams).substr(1);
  signParams.token = token;
  signParams.uid = uid;
  signParams.sign = md5(`${urlStr}global`);

  return signParams;
}

// 充值记录 - 列数据
export const getLogsColumns = (self: any) => {
  const { orderStatus, userType } = self.state.tableFilters;
  // const
  const userTypeData = userType ? [userType] : ['-1'];
  const orderStatusData = typeof orderStatus === 'string' ? orderStatus.split(',') : orderStatus;

  const columns: ColumnProps<StateType>[] = [
    // 充值时间
    {
      title: formatMessage({ id: 'recharge-logs.table.recharge-time' }),
      dataIndex: 'createDate',
      key: 'createDate',
      width: 130,
      render: text => toTime(text),
    },
    // 充值单号
    {
      title: formatMessage({ id: 'recharge-logs.table.order-id' }),
      dataIndex: 'orderId',
      key: 'orderId',
      width: 240,
      render: (text, record) => {
        const { originalOrderId } = record;
        return originalOrderId ? (
          <div>
            <p style={{ margin: '0px' }}>{text}</p>
            <p style={{ margin: '0px' }}>({originalOrderId}原)</p>
          </div>
        ) : (
          text
        );
      },
    },
    // 充值金额
    {
      title: formatMessage({ id: 'recharge-logs.table.recharge-amount' }),
      dataIndex: 'amount',
      key: 'amount',
      width: 130,
      render: text => currency(text),
    },
    // 手续费
    {
      title: formatMessage({ id: 'recharge-logs.table.fee' }),
      dataIndex: 'fee',
      key: 'fee',
      width: 100,
      render: text => currency(text),
    },
    // 到账金额
    {
      title: formatMessage({ id: 'recharge-logs.table.arrival-amount' }),
      dataIndex: 'payAmount',
      key: 'payAmount',
      width: 130,
      render: (text, record) => {
        const val = ['1', '2'].includes(record.status.toString()) ? currency(text) : currency(0);
        return val;
      },
    },
    // 账户名
    {
      title: formatMessage({ id: 'recharge-logs.table.account-name' }),
      dataIndex: 'username',
      key: 'username',
      width: 90,
    },
    // 账户类型
    {
      title: formatMessage({ id: 'recharge-logs.table.account-type' }),
      dataIndex: 'userType',
      key: 'userType',
      width: 120,
      render: text => toUserType(text),
      filters: [
        { text: '全部', value: '-1' },
        { text: '会员', value: '0' },
        { text: '代理', value: '1' },
      ],
      filteredValue: userTypeData,
      filterMultiple: false,
    },
    // 用户层级
    {
      title: formatMessage({ id: 'recharge-logs.table.user-level' }),
      dataIndex: 'userLevel',
      key: 'userLevel',
      width: 120,
    },
    // 充值类型
    // {
    //   title: formatMessage({ id: 'recharge-logs.table.recharge-type' }),
    //   dataIndex: 'limitType',
    //   width: 120,
    //   render: text => toRechargeStatus(text),
    //   filters: [
    //     { text: '全部', value: '-1' },
    //     { text: '普通存款', value: '0' },
    //     { text: '大额存款', value: '1' },
    //   ],
    //   filterMultiple: false,
    //   filteredValue: limitTypeData,
    // },
    // 姓名
    {
      title: formatMessage({ id: 'recharge-repair-table.really-name' }),
      dataIndex: 'reallyName',
      key: 'reallyName',
      width: 90,
      render: text => getElliStyleElement(text, 90),
    },
    // 手机号
    {
      title: formatMessage({ id: 'recharge-repair-table.telephone' }),
      dataIndex: 'telephone',
      key: 'telephone',
      width: 130,
    },
    // 充值方式
    {
      title: '充值方式',
      dataIndex: 'paymentId',
      key: 'paymentId',
      width: 90,
      render: text => toPaymentType(text),
    },
    // 充值商户
    {
      title: formatMessage({ id: 'recharge-logs.table.recharge-merchant' }),
      dataIndex: 'channelId',
      width: 120,
      render: (text, record) => record.merchantName,
    },
    // 商户ID
    {
      title: formatMessage({ id: 'recharge-logs.table.merchant-id' }),
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      width: 130,
      render: text => getElliStyleElement(text, 130),
    },
    // 订单状态
    {
      title: formatMessage({ id: 'recharge-logs.table.order-status' }),
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      width: 120,
      render: (text, record) => (
        <span style={getStyle(record.status, record.subStatus)}>{toRepairStatus(record)}</span>
      ),
      filters: LOGS_STATUS,
      filteredValue: orderStatusData,
    },
    // 到账时间
    {
      title: formatMessage({ id: 'recharge-logs.table.arrival-time' }),
      dataIndex: 'payTime',
      key: 'payTime',
      width: 120,
      render: text => toTime(text),
    },
    // 收款银行
    {
      title: formatMessage({ id: 'recharge-logs.table.arrival-bank' }),
      dataIndex: 'bankName',
      key: 'bankName',
      width: 90,
    },
    // 收款卡
    // {
    //   title: formatMessage({ id: 'recharge-logs.table.arrival-bank-card' }),
    //   dataIndex: 'cardNo',
    //   key: 'cardNo',
    //   width: 120,
    // },
    // 收款人
    {
      title: formatMessage({ id: 'recharge-logs.table.arrival-person' }),
      dataIndex: 'cardUsername',
      key: 'cardUsername',
      width: 90,
    },
    // 付款银行
    // {
    //   title: formatMessage({ id: 'recharge-logs.table.payment-bank' }), // 拿不到
    //   dataIndex: '2',
    //   key: '2',
    //   width: 90,
    // },
    // // 付款卡
    // {
    //   title: formatMessage({ id: 'recharge-logs.table.payment-bank-card' }),
    //   dataIndex: 'remark',
    //   key: 'remark',
    //   width: 130,
    // },
    // 付款人
    {
      title: formatMessage({ id: 'recharge-logs.table.payment-person' }),
      dataIndex: 'fromUser',
      key: 'fromUser',
      width: 90,
      render: (text, record) => (record.keyword && record.keyword.split('|')[0]) || '',
    },
    // 附言
    {
      title: formatMessage({ id: 'recharge-logs.table.post-message' }),
      dataIndex: 'keyword',
      key: 'keyword',
      width: 130,
    },
    // 备注
    {
      title: formatMessage({ id: 'recharge-logs.table.remark' }),
      dataIndex: 'remarkType',
      key: 'remarkType',
      width: 150,
      render: (text, record) => record.newRemark,
      filters: REMARK_STATUS,
      filterMultiple: false,
    },
    // 操作
    {
      title: formatMessage({ id: 'recharge-logs.table.operation' }),
      dataIndex: 'opt',
      key: 'opt',
      width: 170,
      fixed: 'right',
      render: (text, record) => {
        const repairBtn = () => {
          const ele =
            checkShowOpt(record) &&
            checkPermission(self.props.btns, 'new-finance-recharge-logs-repair') ? (
              <Button
                style={{ marginLeft: '0' }}
                type="primary"
                onClick={() => self.handleDetail(record)}
              >
                补单
              </Button>
            ) : null;
          return ele;
        };
        const detailBtn = () => (
          <Button
            type="primary"
            style={{ marginLeft: '5px', background: 'orange', borderColor: 'orange' }}
            onClick={() => self.setState({ rowData: record, detailDialogVisible: true })}
          >
            详情
          </Button>
        );
        return (
          <div>
            {repairBtn()}
            {detailBtn()}
          </div>
        );
      },
    },
  ];
  return columns;
};

// 充值补单 - 创建单号
export const getCreateColumns = (self: any, bankList: any[], getInfo: Function) => {
  const columns: ColumnProps<StateType>[] = [
    // 关联单号
    {
      title: () => (
        <div>
          <span style={{ color: 'red' }}>*</span>
          <FormattedMessage id="recharge-repair-create-dialog-table.relation-id" />
        </div>
      ),
      dataIndex: 'ord',
      width: 250,
      render: () => (
        // 请输入关联单号
        <Input
          style={{ width: '100%' }}
          placeholder={formatMessage({
            id: 'recharge-repair-create-dialog-table.relation-id-placeholder',
          })}
          onPressEnter={(e: any) => {
            if (e.target.value.trim()) getInfo();
          }}
          onChange={(e: any) => {
            const orderId = e.target.value.trim();
            self.setState({ inputOrderId: orderId });
          }}
          onBlur={(e: any) => {
            if (e.target.value) getInfo();
          }}
        />
      ),
    },
    // 充值方式
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.recharge-type' }),
      dataIndex: 'paymentId',
      key: 'paymentId',
      width: 100,
      render: text => toRechargeType(text),
    },
    // 充值通道
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.recharge-channel' }),
      dataIndex: 'channelName',
      key: 'channelName',
      width: 90,
    },
    // 商户号
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.merchant-code' }),
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      width: 150,
      render: text => (
        <span style={{ width: '140px', wordBreak: 'break-all', textAlign: 'center' }}>{text}</span>
      ),
    },
    // 订单金额
    {
      title: () => (
        <div>
          <span style={{ color: 'red' }}>*</span>
          <FormattedMessage id="recharge-repair-create-dialog-table.order-amount" />
        </div>
      ),
      dataIndex: 'amount',
      key: 'amount',
      width: 150,
      render: () => (
        <InputNumber
          style={{ width: '100%' }}
          min={0}
          precision={2}
          onChange={val => {
            self.setState({ inputAmount: val });
          }}
        />
      ),
    },
    // 账户名
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.account-name' }),
      dataIndex: 'username',
      key: 'username',
      width: 90,
    },
    // 收款卡姓名
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.payee-name' }),
      dataIndex: 'cardUsername',
      key: 'cardUsername',
      width: 100,
      // render: () => (
      //   <Input
      //     onChange={(e: any) => {
      //       const obj = { ...recharge };
      //       obj.payeeName = e.target.value;
      //       self.setState({ orderInfo: { ...orderInfo, recharge: { ...obj } } });
      //     }}
      //   />
      // ),
    },
    // 收款卡银行名称
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.payee-bank-name' }),
      dataIndex: 'bankName',
      key: 'bankName',
      width: 130,
      // render: text => (
      //   <Select
      //     defaultValue={text}
      //     style={{ width: 120 }}
      //     onChange={(val: number) => {
      //       const obj = { ...recharge };
      //       obj.payeeBankId = val;
      //       self.setState({ orderInfo: { ...orderInfo, recharge: { ...obj } } });
      //     }}
      //   >
      //     {bankList.map((item: any) => (
      //       <Option key={item.bankId}>{item.bankName}</Option>
      //     ))}
      //   </Select>
      // ),
    },
  ];
  return columns;
};

export const getRelationColumns = () => {
  const columns: ColumnProps<StateType>[] = [
    // 订单号
    {
      title: '订单号',
      dataIndex: 'orderId',
      key: 'orderId',
    },
    // 充值方式
    {
      title: '充值方式',
      dataIndex: 'paymentId',
      key: 'paymentId',
      render: text => toRechargeType(text),
    },
    // 充值通道
    {
      title: '充值通道',
      dataIndex: 'channelName',
      key: 'channelName',
    },
    // 商户号
    {
      title: '商户号',
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      width: 150,
      render: text => (
        <span style={{ width: '140px', wordBreak: 'break-all', textAlign: 'center' }}>{text}</span>
      ),
    },
    // 订单金额
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      render: text => currency(text),
    },
    // 账户名
    {
      title: '账户名',
      dataIndex: 'username',
      key: 'username',
    },
    // 收款卡姓名
    {
      title: '收款卡姓名',
      dataIndex: 'cardUsername',
      key: 'cardUsername',
    },
    // 收款卡银行
    {
      title: '收款卡银行',
      dataIndex: 'bankName',
      key: 'bankName',
    },
    // 订单状态
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (text, record) => toRepairStatus(record),
    },
  ];

  return columns;
};

// 补单操作 -- 详情 -- 系统订单详情列数据
export const getRepairSysColumns = (self: any) => {
  const { bankList } = self.props.recharge.ordinaryAmountData;
  const { bankId } = self.props.data;
  const bankListData = [...bankList];
  if (bankId === 0 || bankId === -1) {
    bankListData.push({ bankId, bankName: '其他' });
  }

  const columns: ColumnProps<StateType>[] = [
    // 充值时间
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.recharge-time' }),
      dataIndex: 'createDate',
      key: 'createDate',
      width: 120,
      render: text => toTime(text),
    },
    // 充值单号
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-id' }),
      key: 'orderId',
      dataIndex: 'orderId',
      width: 120,
      render: (text, record) => {
        const { originalOrderId } = record;
        return originalOrderId ? (
          <div>
            <p style={{ margin: '0px' }}>{text}</p>
            <p style={{ margin: '0px' }}>({originalOrderId}原)</p>
          </div>
        ) : (
          text
        );
      },
    },
    // 状态
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.status' }),
      dataIndex: 'status',
      key: 'status',
      width: 90,
      // render: text => toStatus(text),
      render: (text, record) => toRepairStatus(record),
    },
    // 订单金额
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-amount' }),
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: text => currency(text),
    },
    // 账户名
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.account-name' }),
      dataIndex: 'username',
      key: 'username',
      width: 90,
    },
    // 收款人姓名
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.accept-bank-name' }),
      dataIndex: 'cardUsername',
      key: 'cardUsername',
      width: 90,
      render: (text, record) => {
        const { channelId } = record;
        return channelId === 1001 || channelId === 1003 ? (
          <Input
            defaultValue={record.cardUsername}
            onChange={(e: any) => {
              self.setState({ payeeName: e.target.value });
            }}
          />
        ) : (
          record.cardUsername
        );
      },
    },
    // 收款银行名称
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.payee-bank-name' }),
      dataIndex: 'bankName',
      key: 'bankName',
      width: 120,
      render: (text, record) => {
        const { bankId: id } = record;
        return record.channelId === 1001 || record.channelId === 1003 ? (
          <Select
            style={{ width: '110px' }}
            defaultValue={id}
            onChange={(val: number) => {
              self.setState({ payeeBankId: val });
            }}
          >
            {bankListData.map((item: any) => (
              <Option value={item.bankId} key={item.bankId}>
                {item.bankName}
              </Option>
            ))}
          </Select>
        ) : (
          record.bankName
        );
      },
    },
    // 补单金额
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.make-up-amout' }),
      key: 'makeUpAmount',
      width: 140,
      render: (text, record) => (
        <InputNumber
          min={0}
          style={{ width: '140px' }}
          value={self.state.saveData.amount}
          disabled={!checkShowOpt(record)}
          onChange={val => {
            const saveData = { ...self.state.saveData, amount: val };
            self.setState({ saveData });
          }}
        />
      ),
    },
  ];
  return columns;
};

// 补单操作 -- 详情 -- 第三方订单详情列数据
export const getRepairMerColumns = (self: any) => {
  const { data } = self.props;
  const columns: ColumnProps<StateType>[] = [
    // 入款商户
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.accept-merchant' }),
      dataIndex: 'channelName',
      key: 'channelName',
      render: (text, record) => `${record.channelName || ''} ${record.merchantCode || ''}`,
    },
    // 订单时间
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-time' }),
      dataIndex: 'payDate',
      key: 'payDate',
      render: text => toTime(text),
    },
    // 订单单号
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-code' }),
      dataIndex: 'thirdOrderId',
      key: 'thirdOrderId',
    },
    // 订单状态
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-status' }),
      dataIndex: 'status',
      key: 'status',
      render: text => toMerchantStatus(text),
    },
    // 订单金额
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-amount' }),
      dataIndex: 'amount',
      key: 'amount',
      render: text => currency(text),
    },
    // 姓名
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.really-name' }),
      dataIndex: 'name',
      key: 'name',
    },
    // 操作
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.operation' }),
      dataIndex: 'opt',
      key: 'opt',
      render: () => {
        const ele = checkShowOpt(data) ? (
          // 验证订单状态
          <span className={styles.btnLine} onClick={() => self.handleCheck(data)}>
            {formatMessage({ id: 'recharge-repair-detail-dialog-table.check-status' })}
          </span>
        ) : null;
        return ele;
      },
    },
  ];
  return columns;
};
